/*
 * Created on 2005-8-8
 */
package com.datawise.opencrud.validation.rule;

import java.util.Map;

import org.apache.oro.text.perl.Perl5Util;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;

import com.datawise.opencrud.metadata.CrudMeta;
import com.datawise.opencrud.validation.CrudValidateRuleSupport;

/**
 * 正则表达式校验规则。
 * 
 * @author <a href="mailto:ljglory@126.com">Lujie</a>
 */
public class RegExpressionRule extends CrudValidateRuleSupport 
{
    /**正则表达式*/
	private String regularExpression;

	private static Perl5Util perl5util = new Perl5Util();
	
	/**
	 * 构造方法，用于设置缺省值。
	 */
	public RegExpressionRule()
	{
	    this.setErrorCode("regExpression");
	    this.setDefaultMessage("输入值无法匹配预期的正则表达式");
	}
	
	/**
	 * @see com.datawise.opencrud.validation.CrudValidateRule#validate(org.springframework.validation.Errors, java.lang.String, java.lang.String, java.util.Map, com.datawise.opencrud.metadata.CrudMeta)
	 */
	public void validate(Errors errors, String fieldName, String fieldValue, Map allFieldValueMap, CrudMeta crudMeta)
	{
	    if ( !StringUtils.hasLength(fieldValue) )
	        return;
	    
		try
		{
			if(!perl5util.match(regularExpression,fieldValue))
			{
			    errors.rejectValue(fieldName, this.getErrorCode(), this.getDefaultMessage());
			}
		}
		catch(Exception e)
		{
		    errors.rejectValue(fieldName, this.getErrorCode(), this.getDefaultMessage());
		}
		
	}
	
	/**
	 * @param regularExpression The regularExpression to set.
	 */
	public void setRegularExpression(String regularExpression) 
	{
		this.regularExpression = regularExpression;
	}
}
